package com.cloudalibabaconsumer8084.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cloudalibabacomment8001.entity.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: TODO
 * @Author zx
 * @Date 2024/11/22 14:45
 * @Version 1.0
 */
@RestController
@Slf4j
public class ConsumerController {

    //服务提供者URL
    @Value("${service-url.nacos-user-service}")
    private String SERVICE_URL;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback", fallback = "handlerFallback")
    public JsonResult<String> fallback(@PathVariable Long id) {
        if (id > 3) {
            //通过Ribbon发起远程访问，访问9003/9004
            JsonResult<String> result = restTemplate.getForObject(SERVICE_URL + "/info/" + id, JsonResult.class);
            return result;
        } else {
            throw new RuntimeException("id不能大于3");
        }

    }

    @GetMapping("/consumer/newFallback/{id}")
    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler")
    public JsonResult<String> newFallback(@PathVariable Long id) {
        if (id < 3) {
            //通过Ribbon发起远程访问，访问9003/9004
            JsonResult<String> result = restTemplate.getForObject(SERVICE_URL + "/info/" + id, JsonResult.class);
            return result;
        } else {
            throw new RuntimeException("id不能大于3");
        }

    }

    @GetMapping("/consumer/newFallback3/{id}")
    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler",
            exceptionsToIgnore = {NullPointerException.class})
    public JsonResult<String> newFallback3(@PathVariable Long id) {
        if (id < 3) {
            //通过Ribbon发起远程访问，访问9003/9004
            JsonResult<String> result = restTemplate.getForObject(SERVICE_URL + "/info/" + id, JsonResult.class);
            return result;
        } else {
            throw new NullPointerException("id不能大于3");
        }

    }

    public JsonResult<String> handlerFallback(@PathVariable Long id, Throwable e) {
        return new JsonResult<>(444, "兜底异常handlerFallback，exception内容：" + e.getMessage());
    }

    public JsonResult<String> blockHandler(@PathVariable Long id, BlockException e) {
        return new JsonResult<>(555, "兜底异常blockHandler，exception内容：" + e.getMessage());
    }
}
